package net.sk.china.city.config;

import lombok.extern.slf4j.Slf4j;
import net.sk.china.city.domain.ArActivityRecord;
import net.sk.china.city.mapper.ArActivityMapper;
import net.sk.china.city.mapper.ArActivityRecordMapper;
import net.sk.china.city.mapper.UserMapper;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

@Slf4j
//@Configuration
//@EnableScheduling
public class TaskConfig {

    private ArActivityRecordMapper arActivityRecordMapper;
    private ArActivityMapper arActivityMapper;
    private UserMapper userMapper;

    public TaskConfig(ArActivityMapper arActivityMapper, ArActivityRecordMapper arActivityRecordMapper, UserMapper userMapper) {
        this.arActivityMapper = arActivityMapper;
        this.arActivityRecordMapper = arActivityRecordMapper;
        this.userMapper = userMapper;
    }

    // 每小时的第10分钟开始，每10分钟执行一次，跨小时会留下20分钟的间隙
    @Scheduled(cron = "0 10/10 * * * ?")
    public void activityProcessTask() {
        // 截止报名
        arActivityMapper.endSignup();
    }

    // 每小时的第15分钟开始，每10分钟执行一次，跨小时会留下20分钟的间隙
    @Scheduled(cron = "0 15/10 * * * ? ")
    public void activityCompleteTask() {
        log.info("=====================开始结算任务==========================");
        // 查询的活动有一个条件：status=3，也即必须先截止报名，所以不用担心活动状态的更新乱掉的问题
        List<Long> completeActivityIdList = arActivityMapper.getToBeCompleteActivity();
        if (!completeActivityIdList.isEmpty()) {
            log.info("=================结算中======================");
            // 为志愿者加上积分，并将活动记录设置为已完成
            List<ArActivityRecord> arActivityRecords = arActivityRecordMapper.selectAllActivityRecordByActivityIdList(completeActivityIdList);
            if (!arActivityRecords.isEmpty()) {
                // 先结算积分
                for (ArActivityRecord arActivityRecord : arActivityRecords) {
                    userMapper.addPoint(arActivityRecord.getUserId(), arActivityRecord.getPoint(), arActivityRecord.getWorkHour());
                    arActivityRecordMapper.completeRecord(arActivityRecord.getPkId());
                }
            }
            // 有没有活动记录，都要将活动置为完成
            for (Long activityId : completeActivityIdList) {
                arActivityMapper.completeActivity(activityId);
            }

        }
        log.info("==================结算任务完成一次运行=======================");
    }

}
